{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys,os \n",
    "root_path = os.path.abspath('../')\n",
    "sys.path.append(root_path)\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import math\n",
    "from util.hw_util import *\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "hu = HwUtil()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "查询行情\n",
      "查询行情-完成\n",
      "开始交易日\n",
      "开始交易日-完成\n",
      "查询除权除息行情\n",
      "查询除权除息行情-完成\n"
     ]
    }
   ],
   "source": [
    "#初始化数据\n",
    "#sta_date_str 回测开始时间\n",
    "#end_date_str 回测结束时间\n",
    "#for_day      需要选股当天往前多少个交易日的数据\n",
    "#is_ck        是否使用ck数据库\n",
    "#is_stk       是否初始化北向资金\n",
    "# 此方法仅初始化一次 无需重复执行\n",
    "#\n",
    "# 行情数据\n",
    "# hu.trade_date_list_md\n",
    "# 股票代码数据\n",
    "# hu.trade_date_list_info\n",
    "# 行情数据-除权除息后\n",
    "# hu.trade_date_list_md_xd\n",
    "# 交易日数据\n",
    "# hu.md_trade_date\n",
    "# 回测交易日数组\n",
    "# hu.trade_date_list\n",
    "# 北向资金交易日数据\n",
    "# hu.md_trade_date_stk\n",
    "# 北向资金持仓数据\n",
    "# hu.trade_stk_hold\n",
    "# 选股结果\n",
    "# hu.res_info_data\n",
    "# 计算收益结果\n",
    "# hu.ret_data\n",
    "# 任何地方均可以调用\n",
    "hu.init_md_trade_sec_data(sta_date_str='2021-11-17',end_date_str='2021-11-17',for_day=120,is_fmc=False,is_stk=False,is_mtss=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2021-11-17\n"
     ]
    }
   ],
   "source": [
    "#开始回测\n",
    "#hu           数据类\n",
    "#size_sec     每天选多少支股票 选股方法的sort有值会根据sort排序 传0则全部\n",
    "#for_day      需要选股当天往前多少个交易日的数据\n",
    "def for_fun(select_sec_md_data,day_date):\n",
    "    colums = ['code','pre_close','sort']\n",
    "    select_sec_data = pd.DataFrame(columns=colums)\n",
    "    sec_code = select_sec_md_data.iloc[0].code\n",
    "    jk_df_a = hu.md_and_rps_data[(hu.md_and_rps_data['trade_date']<=datetime.strptime(day_date, \"%Y-%m-%d\"))&(hu.md_and_rps_data['code']==sec_code)]\n",
    "    jk_df_a_next = hu.md_and_rps_data[(hu.md_and_rps_data['trade_date']==datetime.strptime(day_date, \"%Y-%m-%d\"))&(hu.md_and_rps_data['code']==sec_code)]\n",
    "    macd_data = pd.DataFrame(columns = jk_df_a.columns)\n",
    "    macd_data = macd_data.append(jk_df_a)\n",
    "    #均线数据\n",
    "    jk_df_a['MA60'] = jk_df_a['close'].rolling(60).mean()\n",
    "    jk_df_a['MA20'] = jk_df_a['close'].rolling(20).mean()\n",
    "    jk_df_a['MA10'] = jk_df_a['close'].rolling(10).mean()\n",
    "    jk_df_a['MA5'] = jk_df_a['close'].rolling(5).mean()\n",
    "\n",
    "    next_open = 0\n",
    "    next_close = 0\n",
    "    if len(jk_df_a_next)>0:\n",
    "        next_open = jk_df_a_next.iloc[0].open\n",
    "        next_close = jk_df_a_next.iloc[0].close\n",
    "    jk_df_a.sort_values(\"trade_date\",inplace=True,ascending=False)\n",
    "    #数据不够\n",
    "    if len(jk_df_a)<2:\n",
    "        return None\n",
    "    jk_df_a_size = jk_df_a[0:10]\n",
    "    pre_s = jk_df_a_size.iloc[1]\n",
    "    last_s = jk_df_a_size.iloc[0]\n",
    "    pre_close_money = pre_s['close']*1.10-0.01\n",
    "    #\n",
    "    if last_s['close']>=pre_close_money:\n",
    "        return None\n",
    "    #去除昨日阴线得股票\n",
    "    if pre_s['close']<pre_s['open']:\n",
    "        return None\n",
    "    #去除低开得股票\n",
    "    # if pre_s['close']>last_s['open']:\n",
    "    #     return None\n",
    "    #去除最高价等于收盘价得股票\n",
    "    # if last_s['close']==last_s['high']:\n",
    "    #     return None\n",
    "    #去除今日K线 上影大于1个点\n",
    "    last_close_m = last_s['close']*0.01\n",
    "    last_up_m = last_s['high']-last_s['close']\n",
    "    if last_up_m<last_close_m:\n",
    "        return None\n",
    "    #去除今收低于5日线\n",
    "    if last_s['close']<last_s['MA5']:\n",
    "        return None\n",
    "    #去除RPS低于87\n",
    "    if last_s['RPS5']<87:\n",
    "        return None\n",
    "    if last_s['RPS20']<87:\n",
    "        return None\n",
    "    if last_s['RPS50']<87:\n",
    "        return None\n",
    "    new_change_pct = (last_s['close']-pre_s['close'])/pre_s['close']*100\n",
    "    #去除当日涨幅小于5%\n",
    "    if new_change_pct<5.0:\n",
    "        return None\n",
    "    #获取120日最高点\n",
    "    high_120_max = jk_df_a['high'].max()\n",
    "    #获取120日距离今天之间得最低点\n",
    "    c_120_jk_df_a = jk_df_a[jk_df_a['trade_date']>jk_df_a[jk_df_a['high']==high_120_max].iloc[0].trade_date]\n",
    "    if len(c_120_jk_df_a)<5:\n",
    "        return None\n",
    "    if len(c_120_jk_df_a)>60:\n",
    "        return None\n",
    "    low_120_c_min = c_120_jk_df_a['low'].min()\n",
    "    #阶段最大下跌幅度不超过-46%\n",
    "    if (low_120_c_min/high_120_max)<0.54:\n",
    "        return None\n",
    "    select_jk = jk_df_a_size[jk_df_a_size['money']==jk_df_a_size['money'].max()].iloc[0]\n",
    "    if select_jk['money']!=last_s['money']:\n",
    "        return None\n",
    "    select_sec_data.loc[select_sec_data.shape[0]] = {'code':sec_code,'pre_close':last_s['close'],'sort':0}\n",
    "    # new_change_pct = (last_s['close']-pre_s['close'])/pre_s['close']*100\n",
    "    # if new_change_pct>3.0:\n",
    "    # 计算EMA(12)和EMA(16)\n",
    "    # macd_data['EMA12'] = macd_data['close'].ewm(alpha=2 / 13, adjust=False).mean()\n",
    "    # macd_data['EMA26'] = macd_data['close'].ewm(alpha=2 / 27, adjust=False).mean()\n",
    "    # # 计算DIFF、DEA、MACD\n",
    "    # macd_data['DIFF'] = macd_data['EMA12'] - macd_data['EMA26']\n",
    "    # macd_data['DEA'] = macd_data['DIFF'].ewm(alpha=2 / 10, adjust=False).mean()\n",
    "    # macd_data['MACD'] = 2 * (macd_data['DIFF'] - macd_data['DEA'])\n",
    "    # # 上市首日，DIFF、DEA、MACD均为0\n",
    "    # macd_data['DIFF'].iloc[0] = 0\n",
    "    # macd_data['DEA'].iloc[0] = 0\n",
    "    # macd_data['MACD'].iloc[0] = 0\n",
    "    # if len(macd_data)>3:\n",
    "    #     data_macd_s = macd_data.iloc[-1]\n",
    "    #     data_macd_s_diff = math.floor(data_macd_s.DIFF*100.00)\n",
    "    #     data_macd_s_dea = math.floor(data_macd_s.DEA*100.00)\n",
    "    #     if (data_macd_s_diff>0)&(data_macd_s_dea>0):\n",
    "    #         if (data_macd_s_diff-data_macd_s_dea)>0:\n",
    "    #             macd1 = math.floor(macd_data.iloc[-1].MACD*100.00)\n",
    "    #             macd2 = math.floor(macd_data.iloc[-2].MACD*100.00)\n",
    "    #             macd3 = math.floor(macd_data.iloc[-3].MACD*100.00)\n",
    "    #             if (macd3<0)&(macd2>0)&(macd1>macd2):\n",
    "                    #  select_sec_data.loc[select_sec_data.shape[0]] = {'code':sec_code,'pre_close':last_s['close'],'sort':0}\n",
    "    # data_macd = macd_data[macd_data['trade_date']==datetime.strptime(day_date, \"%Y-%m-%d\").date()]\n",
    "    # data_macd = macd_data[-1:-2]\n",
    "    # print(macd_data.iloc[-1])\n",
    "    # jk_df_a_size = jk_df_a_size.reset_index(drop=True)\n",
    "    # jk_df_a = jk_df_a.reset_index(drop=True)\n",
    "    # jk_df_a['i'] = jk_df_a.index\n",
    "    # if last_s['close']>(pre_s['close']*1.05):\n",
    "    #     if last_s['close']<last_s['MA60']:\n",
    "    #         if last_s['close']<last_s['MA20']:\n",
    "    #             if last_s['close']>last_s['MA5']:\n",
    "    #                 select_jk = jk_df_a_size[jk_df_a_size['money']==jk_df_a_size['money'].max()].iloc[0]\n",
    "    #                 if select_jk['money']==last_s['money']:\n",
    "    #                     high_jk = jk_df_a[jk_df_a['high']==jk_df_a['high'].max()].iloc[0]\n",
    "    #                     # print(high_jk['i'])\n",
    "    #                     if high_jk['i']<30 and high_jk['i']>7:\n",
    "    #                         if high_jk['high']<(last_s['close']*1.20):\n",
    "    #                     # if select_jk['code']=='603618.SH':\n",
    "    #                     #     print(jk_df_a)\n",
    "    #                     #     print(select_jk)\n",
    "    #                     #     print(pre_s)\n",
    "    #                         # jk_df_a.max['high']\n",
    "    #                             select_sec_data.loc[select_sec_data.shape[0]] = {'code':sec_code,'pre_close':last_s['close'],'sort':0}\n",
    "    # print(jk_df_a)\n",
    "    # if len(macd_data)>3:\n",
    "    #     data_macd_s = macd_data.iloc[-1]\n",
    "    #     data_macd_s_diff = math.floor(data_macd_s.DIFF*100.00)\n",
    "    #     data_macd_s_dea = math.floor(data_macd_s.DEA*100.00)\n",
    "    #     if (data_macd_s_diff>0)&(data_macd_s_dea>0):\n",
    "    #         if (data_macd_s_diff-data_macd_s_dea)>0:\n",
    "    #             macd1 = math.floor(macd_data.iloc[-1].MACD*100.00)\n",
    "    #             macd2 = math.floor(macd_data.iloc[-2].MACD*100.00)\n",
    "    #             macd3 = math.floor(macd_data.iloc[-3].MACD*100.00)\n",
    "    #             if (macd3<0)&(macd2>0)&(macd1>macd2):\n",
    "    #                 select_jk = jk_df_a[jk_df_a['money']==jk_df_a['money'].max()].iloc[0]\n",
    "    #                 if select_jk['money']==last_s['money']:\n",
    "    #                     # if select_jk['code']=='603618.SH':\n",
    "    #                     #     print(jk_df_a)\n",
    "    #                     #     print(select_jk)\n",
    "    #                     #     print(pre_s)\n",
    "    #                         # jk_df_a.max['high']\n",
    "    #                     select_sec_data.loc[select_sec_data.shape[0]] = {'code':sec_code,'pre_close':last_s['close'],'sort':0}\n",
    "                    # new_change_pct = (last_s['close']-pre_s['close'])/pre_s['close']*100\n",
    "    #                 if new_change_pct>3.0:\n",
    "        # select_sec_data.loc[select_sec_data.shape[0]] = {'code':sec_code,'pre_close':last_s['close'],'sort':new_change_pct}\n",
    "    return select_sec_data\n",
    "\n",
    "hu.start_test(size_sec=0,for_day=120,for_fun=for_fun)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "{条件四KD6}\n",
    "{如果最近15天之内有阶段新低价格（且新低价格是过去50日内的最低价）且最新价格没有创一年新高的股票，淘汰}\n",
    "\n",
    "H120:=HHV(H,120); {120内的最高点}\n",
    "\n",
    "T1:=HHVBARS(H,120); {120内的最高点距今天的天数}\n",
    "\n",
    "L120:=LLV(L,T1+1); {120内的最高点至今，这个区间的最低点}\n",
    "\n",
    "FKD61:=LLV(L,40)/HHV(H,120)>0.5;{40日内最低价不低于120日内最高价的一半}\n",
    "\n",
    "FKD6:=FKD61 OR FKD250;{40日内最低价不低于120日内最高价的一半，或者创250日的最高价}\n",
    "\n",
    "KD6:=L120/H120>0.54 AND FKD6; {阶段最大下跌幅度不超过-46%}\n",
    "\n",
    "{条件五KD20：成交量和涨幅限制要求}\n",
    "\n",
    "FKD21:=AMO=HHV(AMO,10);{创10日的最高成交金额}\n",
    "\n",
    "FKD22:=C/REF(C,1)>1.099;{当日上涨超过9.9%}\n",
    "\n",
    "KD20:=FKD21 OR FKD22; {创10日的最高成交金额，或者当日上涨超过9.9%}\n",
    "\n",
    "{ KD3 AND AND KD7 AND KD8未知};\n",
    "\n",
    "KDZDT:KD1 AND KD2 AND KD5 AND KD6 AND KD4 AND KD20;{ KD3 AND AND KD7 AND KD8未知};"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for index, row in hu.res_info_data.iterrows():\n",
    "    row.size = len(row.code)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>code</th>\n",
       "      <th>size</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2021-11-17</td>\n",
       "      <td>[605169.SH]</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         date         code size\n",
       "0  2021-11-17  [605169.SH]    3"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hu.res_info_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hu.res_info_data.to_parquet(\"data/210101-211111-kdzd.parquet\")\n",
    "# hu.res_info_data = pd.read_parquet(\"data/210101-211111-kdzd.parquet\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hu.trade_date_list_md_xd['trade_date'] = hu.trade_date_list_md_xd['trade_date'].dt.date\n",
    "# hu.trade_date_list_md_xd['trade_date'] = pd.to_datetime(hu.trade_date_list_md_xd['trade_date'].astype(str))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sec_filter(pre_md_data,md):\n",
    "    # print(md)\n",
    "    # print(pre_md_data.iloc[-1])\n",
    "    if md.close>=(pre_md_data.iloc[-1].close*1.09):\n",
    "        return False\n",
    "    else:\n",
    "        return True\n",
    "#hu             数据类\n",
    "#num_sell_day   几天后卖出 1为明天卖出\n",
    "#test_money     回测金额\n",
    "#day_num        往前几天买入 默认1 勿修改\n",
    "#sell_par       卖出字段 open close\n",
    "#buy_par        买入字段 open close\n",
    "#hold_money_r   持仓占比 0.5 or 1.0\n",
    "hu.start_test_profit(num_sell_day=1,test_money=1000000,day_num=1,sell_par='close',buy_par='close',hold_money_r=1,sec_filter=sec_filter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sec_filter(pre_md_data,md):\n",
    "    # print(md)\n",
    "    # print(pre_md_data.iloc[-1])\n",
    "    if md.close>=(pre_md_data.iloc[-1].close*1.09):\n",
    "        return False\n",
    "    else:\n",
    "        return True\n",
    "\n",
    "def start_test_profit_hold(num_sell_day:int,test_money:float,day_num:int,sell_par:str,buy_par:str,hold_money_r:float,sec_filter):\n",
    "        print(\"开始收益统计\")\n",
    "        del hu.ret_data\n",
    "        buy_fee = 0.0002\n",
    "        sell_fee = 0.0012\n",
    "        hold_sum = 3\n",
    "        stop_win = 1.15\n",
    "        stop_lose = 0.98\n",
    "        lose_num = 0\n",
    "        max_lose_num = 30\n",
    "        stop_open_day = 0\n",
    "        l_stop_open_day = 0\n",
    "        hu.ret_data = pd.DataFrame(columns=['date','code','buy','sell','return','sum_return','buy_fee','sell_fee','day_num'])\n",
    "        hold_sec = pd.DataFrame(columns=['code','buy','vol','buy_money','buy_money_fee','day_num','lose_money','win_money'])\n",
    "        g_money = test_money\n",
    "        k_money = test_money\n",
    "        for index, row in hu.res_info_data.iterrows():\n",
    "            date = datetime.strptime(row['date'], \"%Y-%m-%d\").date()\n",
    "            print(date)\n",
    "            code_list = row['code']\n",
    "            ca_hold = hold_sum-len(hold_sec)\n",
    "            d_k_moeny = k_money/ca_hold\n",
    "            #sell\n",
    "            if len(hold_sec)>0:\n",
    "                del_index = []\n",
    "                for index, hold in hold_sec.iterrows():\n",
    "                    sell_code = hold.code\n",
    "                    sell_buy_money = hold.buy\n",
    "                    to_day_md_data = hu.trade_date_list_md_xd[(hu.trade_date_list_md_xd['trade_date']==date)&(hu.trade_date_list_md_xd['code']==sell_code)]\n",
    "                    pre_md_data = hu.trade_date_list_md_xd[(hu.trade_date_list_md_xd['trade_date']<date)&(hu.trade_date_list_md_xd['code']==s_code)]\n",
    "                    if len(to_day_md_data)>0:\n",
    "                        sell_md = to_day_md_data.iloc[0]\n",
    "                        sell_money = sell_md[sell_par]\n",
    "                    if len(pre_md_data)>0:\n",
    "                        pre_close = pre_md_data.iloc[-1].close\n",
    "                    if pre_close<=0:\n",
    "                        continue\n",
    "                    if sell_money<=0:\n",
    "                        continue\n",
    "                    if sell_money<=(pre_close*1.09):\n",
    "                        continue\n",
    "                    if sell_money>=hold.win_money:\n",
    "                        #stop win\n",
    "                        sell_buy_vol = hold.vol\n",
    "                        sell_sec_money = round(sell_money*sell_buy_vol,2)\n",
    "                        sell_sec_fee_money = round(sell_sec_money*sell_fee,2)\n",
    "                        del_index.append(index)\n",
    "                        g_ret = sell_sec_money-hold.buy_money\n",
    "                        g_money = g_money+(g_ret-sell_sec_fee_money-hold.buy_money_fee)\n",
    "                        hu.ret_data.loc[hu.ret_data.shape[0]] = {'date':date,'code':sell_md.code,'buy':hold.buy_money,'sell':sell_sec_money,'return':g_ret,\"sum_return\":g_money,'buy_fee':hold.buy_money_fee,'sell_fee':sell_sec_fee_money,'day_num':hold.day_num}\n",
    "                        k_money = k_money+sell_sec_money-buy_sec_fee_money\n",
    "                        lose_num = 0\n",
    "                    elif sell_money<=hold.lose_money:\n",
    "                        #stop lose\n",
    "                        sell_buy_vol = hold.vol\n",
    "                        sell_sec_money = round(sell_money*sell_buy_vol,2)\n",
    "                        sell_sec_fee_money = round(sell_sec_money*sell_fee,2)\n",
    "                        del_index.append(index)\n",
    "                        g_ret = sell_sec_money-hold.buy_money\n",
    "                        g_money = g_money+(g_ret-sell_sec_fee_money-hold.buy_money_fee)\n",
    "                        hu.ret_data.loc[hu.ret_data.shape[0]] = {'date':date,'code':sell_md.code,'buy':hold.buy_money,'sell':sell_sec_money,'return':g_ret,\"sum_return\":g_money,'buy_fee':hold.buy_money_fee,'sell_fee':sell_sec_fee_money,'day_num':hold.day_num}\n",
    "                        k_money = k_money+sell_sec_money-buy_sec_fee_money\n",
    "                        lose_num = lose_num+1\n",
    "                        if lose_num>=max_lose_num:\n",
    "                            l_stop_open_day = 1\n",
    "                    else:\n",
    "                        if sell_money>sell_buy_money:\n",
    "                            #win\n",
    "                            pch = round((sell_money-sell_buy_money)/sell_buy_money,2)*100\n",
    "                            # print(pch)\n",
    "                            # if pch>=30.00 and pch<40.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.30,2)\n",
    "                            # elif pch>=25.00 and pch<30.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.25,2)\n",
    "                            # elif pch>=20.00 and pch<25.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.20,2)\n",
    "                            # elif pch>=15.00 and pch<20.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.15,2)\n",
    "                            # elif pch>=10.00 and pch<15.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.10,2)\n",
    "                            # elif pch>=5.00 and pch<10.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = round(sell_buy_money*1.05,2)\n",
    "                            # if pch>0.00:\n",
    "                            #     hold_sec.loc[index,'lose_money'] = sell_buy_money\n",
    "                        day_num_d = hold.day_num+1\n",
    "                        hold_sec.loc[index,'day_num'] = day_num_d\n",
    "                if len(del_index)>0:\n",
    "                    hold_sec = hold_sec.drop(del_index)\n",
    "                    hold_sec = hold_sec.reset_index(drop=True)\n",
    "                    if ca_hold == 0:\n",
    "                        d_k_moeny = k_money/len(del_index)\n",
    "                    del_index = []\n",
    "            if l_stop_open_day>0:\n",
    "                if stop_open_day<=l_stop_open_day:\n",
    "                    l_stop_open_day = 0\n",
    "                    lose_num = 0\n",
    "                else:\n",
    "                    l_stop_open_day = l_stop_open_day+1\n",
    "                continue\n",
    "            for s_code in code_list:\n",
    "                if len(hold_sec)<hold_sum:\n",
    "                    #buy\n",
    "                    to_day_md_data = hu.trade_date_list_md_xd[(hu.trade_date_list_md_xd['trade_date']==date)&(hu.trade_date_list_md_xd['code']==s_code)]\n",
    "                    # next_md_data = hu.trade_date_list_md_xd[(hu.trade_date_list_md_xd['trade_date']>date)&(hu.trade_date_list_md_xd['code']==s_code)]\n",
    "                    pre_md_data = hu.trade_date_list_md_xd[(hu.trade_date_list_md_xd['trade_date']<date)&(hu.trade_date_list_md_xd['code']==s_code)]\n",
    "                    if len(hold_sec[hold_sec.code==s_code])>0:\n",
    "                        continue\n",
    "                    if len(to_day_md_data)>0:\n",
    "                        md = to_day_md_data.iloc[0]\n",
    "                        buy_money = md[buy_par]\n",
    "                    if buy_money==0:\n",
    "                        continue\n",
    "                    is_sec_filter = sec_filter(pre_md_data,md)\n",
    "                    if is_sec_filter==True:\n",
    "                        buy_sec_vol = d_k_moeny/(buy_money*100)\n",
    "                        buy_sec_vol = round(buy_sec_vol,0)*100\n",
    "                        buy_sec_money = round(buy_sec_vol*buy_money,2)\n",
    "                        buy_sec_fee_money = round(buy_sec_money*buy_fee,2)\n",
    "                        lose_sec_money = round(buy_money*stop_lose,2)\n",
    "                        win_sec_money = round(buy_money*stop_win,2)\n",
    "                        hold_sec.loc[hold_sec.shape[0]] = {'code':md.code,'buy':buy_money,'vol':buy_sec_vol,'buy_money':buy_sec_money,'buy_money_fee':buy_sec_fee_money,'day_num':1,'lose_money':lose_sec_money,'win_money':win_sec_money}\n",
    "                        # hu.ret_data.loc[hu.ret_data.shape[0]] = {'date':date,'code':md.code,'buy':buy_sec_money,'sell':0,'return':0,\"sum_return\":0,'buy_fee':buy_sec_fee_money,'sell_fee':0}\n",
    "                        k_money = k_money-buy_sec_money-buy_sec_fee_money\n",
    "                buy_money = 0\n",
    "                sell_money = 0\n",
    "        print(\"收益统计完成\")\n",
    "        # self.p_profit(test_money)\n",
    "start_test_profit_hold(num_sell_day=1,test_money=1000000,day_num=3,sell_par='open',buy_par='open',hold_money_r=1,sec_filter=sec_filter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "abb = hu.ret_data\n",
    "abb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "len(hu.ret_data[(hu.ret_data['return']>0)&(hu.ret_data['day_num']>20)])\n",
    "hu.ret_data[(hu.ret_data['return']<0)&(hu.ret_data['day_num']>20)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hu.p_profit(test_money=1000000)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "047edc17978fcec36365898495b1b6de8a14521ee4f737035e20a6ab22989f99"
  },
  "kernelspec": {
   "display_name": "Python 3.9.4 64-bit",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
